import { useState, useEffect, createContext, useContext} from 'react';


const StyleThemeContext = createContext(null);

const themeConfig = [
    { key: 'light', label: '亮色模式',},
    { key: 'dark', label: '暗黑模式',  },
    { key: 'followSystem', label: '跟随系统', },
];
export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
    const [theme, setTheme] = useState([localStorage.getItem('sysTheme') ?? 'light']);

   
    useEffect(() => {
        const currentTheme = themeConfig.find(item => item.key === theme[0]);
        const darkThemeMq = window.matchMedia("(prefers-color-scheme: dark)");
        const handleSystemThemeChange = (e: MediaQueryListEvent) => {
            if (e.matches) {
                document.body.setAttribute('arco-theme', 'dark');
            } else {
                document.body.removeAttribute('arco-theme');
            }
        };

        if (currentTheme?.key === 'light') {
            document.body.removeAttribute('arco-theme');
        } else if (currentTheme?.key === 'dark') {
            document.body.setAttribute('arco-theme', 'dark');
        } else if (currentTheme?.key === 'followSystem') { 
            if (darkThemeMq.matches) {
                document.body.setAttribute('arco-theme', 'dark');
            } else {
                document.body.removeAttribute('arco-theme');
            }
        }
        
        if (currentTheme?.key) {
            localStorage.setItem('sysTheme', currentTheme.key);
        }
        darkThemeMq.addEventListener('change', handleSystemThemeChange);

        return () => {
            darkThemeMq.removeEventListener('change', handleSystemThemeChange);
        };
    }, [theme]);
    

    return (
        <StyleThemeContext.Provider value={{theme, setTheme}}>
            { children }
        </StyleThemeContext.Provider>
    )
}




// eslint-disable-next-line react-refresh/only-export-components
export const useThemeContext = () => {
    const context = useContext(StyleThemeContext);
    if (!context) {
      throw new Error('useCart must be used within a StyleThemeContext');
    }
    return context;
}